const jwt=require("jsonwebtoken")

const {TOKEN_LIST,TOKEN_KEY}=require("../config/index")

module.exports = (options, app) => {
    return async function auth(ctx, next) {
        var url=""
        if(ctx.request.url.includes("?")){
            url=ctx.request.url.split('?')[0]
        }else{
            url=ctx.request.url
        }
        // const {url}=ctx.request
        // console.log(url);
        const flag=TOKEN_LIST.includes(url)
        // console.log(flag);
        if(!flag){
            const token=ctx.request.headers["authorization"]
            if(!token){
                ctx.status=401
                ctx.body={
                    code:"1002",
                    msg:"token不存在"
                }
            }else{
                const {exp}=jwt.verify(token,TOKEN_KEY)
                if(+new Date()>exp){
                    ctx.status=401
                    ctx.body={
                        code:"1002",
                        msg:"token已失效"
                    }
                }else{
                    await next()
                }
            }
        }else{
            await next()
        }
    };
  };